package com.turing.data.scripts.xgpsgg.filter

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.turing.common.util.FileUtils
import com.turing.common.util.Log
import com.turing.common.util.StringUtils
import com.turing.data.vo.out.review.DependParamsVO
import com.turing.data.vo.out.review.TaskElementVO

import java.text.DecimalFormat


class InitialAllotmentQuantity_12352_r15_filter {

    public static void main(String[] args) {
        DependParamsVO param = new DependParamsVO()
        param.setJSONPathMap(new LinkedHashMap<String, String>())
//        param.getJSONPathMap().put("abc", "http://media.tlrobot.com/group1/M00/0C/29/rBIHD2CjdRiAPV_eAACdNH_q44831.json")
//        param.getJSONPathMap().put("abc", "/Users/luoshiwei/Desktop/tmp/ex/extractor/e675314b-1c3b-4bb7-9a9f-ef5c268b7b6d/688316_20210305_1/json/688316_20210305_1_converted.json")
        param.getJSONPathMap().put("abc", "C:\\Users\\14771\\Desktop\\华纳药厂：华纳药厂首次公开发行股票并在科创板上市网下初步配售结果及网上中签结果公告_converted.json")
        List<TaskElementVO.DrawResultVO> s = doConvert(param)
        for (int z = 0; z < s.size(); z++) {
            def get = s.get(z)
            println(get.text)
        }
    }

    static List<TaskElementVO.DrawResultVO> doConvert(DependParamsVO dependParams) {
//        def REGEX_COMPANY_1 = /.*银华.*/
//        def REGEX_COMPANY_1 = /.*/
        String SEARCH_TITLE = "初步配售数量（股）"

        String[] Search_Titles = ["初步配售数量（股）", "获配股数（股）", "获配股数（万股）", "获配数量（股）", "初步配售获配股数/股", "配售数量（股）","初步配售股数（股）","最终获配数量（手）","配售股数（股）","初步配售数（股）"]
        Date begin = new Date()
        Date end = new Date()

        List<String> titleList = new LinkedList<>()
        Map<String, String> oldAndNewTitleMap = new HashMap<>()
        Map<String, String> titleAndValueMap = new HashMap<>()

        List<String> keys = dependParams.getJSONPathMap().keySet() as List<String>
        List<TaskElementVO.DrawResultVO> finalResults = new ArrayList<>()

        for (int z = 0; z < keys.size(); z++) {
            String path = dependParams.getJSONPathMap().get(keys.get(z))
            String format_json_path = "/Users/luoshiwei/Desktop/response.json"

            if (!StringUtils.isEmpty(path)) {
                format_json_path = path
            }

            begin = new Date()
            String jsonString = FileUtils.loadJson(format_json_path)

            List<String> newTitleList = ["序号", "投资者名称", "配售对象名称", "证券账户", "申购数量（万股）",
                                         "初步配售数量（股）", "获配金额（元）",
                                         "经纪佣金（元）", "合计应缴（元）", "分类"]
            List<String> oldTitleList = ["序号", "投资者名称", "配售对象名称", "证券账户", "申购数量（万股）",
                                         "初步配售数量（股）", "获配金额（元）",
                                         "经纪佣金（元）", "合计应缴（元）", "分类"]
            end = new Date()
            println "load json: " + (end.getTime() - begin.getTime()) / 1000 / 1000


            //标题映射
            for (int i = 0; i < newTitleList.size(); i++) {
                String newTitle = newTitleList[i]
                String oldTitle = oldTitleList[i]
                oldAndNewTitleMap.put(oldTitle, newTitle)
            }


            boolean foundTitle = false

            begin = new Date()
            JSONArray formatArr = JSONArray.parse(jsonString)
            end = new Date()
            println "parse json array: " + (end.getTime() - begin.getTime()) / 1000 / 1000

            begin = new Date()
            println begin
            for (int pageNo = 0; pageNo < formatArr.size(); pageNo++) {
                JSONObject pageObj = formatArr.getJSONObject(pageNo)
                JSONArray paraArr = pageObj.getJSONArray("paragraphs")
                for (int paragraphsNo = 0; paragraphsNo < paraArr.size(); paragraphsNo++) {

                    JSONObject paraObj = paraArr.getJSONObject(paragraphsNo)
                    JSONArray lineArr = paraObj.getJSONArray("lines")

                    //每一行
                    for (int line = 0; line < lineArr.size(); line++) {
                        titleAndValueMap = new HashMap<>()
                        JSONObject lineObj = lineArr.getJSONObject(line)
                        String lineId = lineObj.getString("lineId")
                        if (JSON.isValidArray(lineObj.getString("cells"))) {
                            JSONArray objContentArr = lineObj.getJSONArray("cells")
                            if (!StringUtils.isEmpty(objContentArr)) {

                                if (!foundTitle && objContentArr.size()>6) {
                                    int foundTitleNum = 0

                                    if (!strContains(Search_Titles, objContentArr.toString().replace("\r", "").replace("\\r", ""))) {
                                        continue
                                    }

                                    for (int i = 0; i < objContentArr.size(); i++) {
                                        JSONObject objContentObj = objContentArr.getJSONObject(i)
                                        String objContentString = objContentObj.getString("objContent")
                                        if (objContentString.contains("\r")) {
                                            objContentString = objContentString.replace("\r", "")
                                        }
                                        //标题栏
                                        if (oldTitleList.contains(objContentString)
                                                || newTitleList.contains(objContentString)
                                                || arrContains(Search_Titles, objContentString)) {
                                            foundTitleNum++

                                        }

                                        String title = oldAndNewTitleMap.get(objContentString)
                                        if (!StringUtils.isEmpty(title)) {
                                            titleList.add(title)
                                        } else {
                                            titleList.add(objContentString)
                                        }

                                    }



                                    if (foundTitleNum >= 3) {
                                        foundTitle = true
                                    } else {
                                        titleList = new LinkedList<>()
                                    }


                                } else {
                                    def wordCount = 0
                                    //每一列
                                    for (int column = 0; column < objContentArr.size(); column++) {
                                        JSONObject objContentObj = objContentArr.getJSONObject(column)
                                        String objContentString = objContentObj.getString("objContent")
                                        def cWordCount = objContentString.length()
                                        if (objContentString.contains("\r")) {
                                            objContentString = objContentString.replace("\r", "")
                                        }
                                        //具体数值栏
                                        if (foundTitle) {
                                            String title = titleList[column]
                                            if (title != null && !StringUtils.isEmpty(title)) {
                                                titleAndValueMap.put(title, objContentString)
                                            }
                                            String businessValue = titleAndValueMap.get(SEARCH_TITLE)
                                            if (!StringUtils.isEmpty(businessValue) && (title != null &&
                                                    (title.contains(SEARCH_TITLE) || Search_Titles.contains(title)))) {
                                                TaskElementVO.DrawResultVO drawResultVO = new TaskElementVO.DrawResultVO()
//                                                    objContentString = objContentString.replace(",","")
                                                drawResultVO.setBusinessValue(objContentString)
                                                drawResultVO.setText(objContentString)
                                                drawResultVO.setPara_info([lineId])
                                                drawResultVO.setPos_info([wordCount, cWordCount + wordCount])
                                                drawResultVO.setPage(lineId.split("_")[1] as Integer)
                                                drawResultVO.setChildTaskSn(keys.get(z))
                                                drawResultVO.setType(1)
                                                if(!Search_Titles.contains(objContentString)){
                                                    finalResults.add(drawResultVO)
                                                }
                                            }
                                        }
                                        wordCount += cWordCount
                                    }
                                }
                            }
                        }
                    }
                }
            }




            end = new Date()
            println end
            println "ex elements: " + (end.getTime() - begin.getTime()) / 1000 / 1000
        }

        Log.info(">>>>>>>>>>>>>>>>>初步配售数量（股）的结果对象有"+finalResults.size()+"个")

        if(finalResults.size()==0){
            Map<String, List<TaskElementVO.DrawResultVO>> relatedMap = dependParams.relatedBusiElements
            List<TaskElementVO.DrawResultVO> AllotmentAmountMap = relatedMap.get("投资者名称")
            if (AllotmentAmountMap.size() > 0) {
                for (int i = 0; i < AllotmentAmountMap.size(); i++) {
                    TaskElementVO.DrawResultVO defaultDrawResultVO = new TaskElementVO.DrawResultVO()
                    defaultDrawResultVO.setText("")
                    defaultDrawResultVO.setBusinessValue("")
                    defaultDrawResultVO.setStart(0)
                    defaultDrawResultVO.setEnd(1)
                    defaultDrawResultVO.setDegree("0")
                    defaultDrawResultVO.setEndLineNo(0)
                    defaultDrawResultVO.setPara_info([])
                    defaultDrawResultVO.setPos([])
                    defaultDrawResultVO.setPos_info([0,1])
                    defaultDrawResultVO.setStartLineNo(0)
                    defaultDrawResultVO.setSequence(UUID.randomUUID().toString())
                    defaultDrawResultVO.setFirstSequence(1)
                    defaultDrawResultVO.setSubProductId(0)
                    defaultDrawResultVO.setNextSequence("")
                    defaultDrawResultVO.setType(1)
                    defaultDrawResultVO.setChildTaskSn("")

                    finalResults.add(defaultDrawResultVO)
                }
            }else {
                TaskElementVO.DrawResultVO defaultDrawResultVO = new TaskElementVO.DrawResultVO()
                defaultDrawResultVO.text = ""
                finalResults.add(defaultDrawResultVO)
            }
        }else {
            for(TaskElementVO.DrawResultVO resultVO : finalResults){
                if(resultVO.businessValue.size()>7){
                    replacePoint(resultVO)
                }
            }
        }

        return finalResults
    }

    static boolean arrContains(String[] Search_Titles, String objContentString) {
        if (Search_Titles.contains(objContentString)) {
            return true
        }
        for (i in 0..<Search_Titles.length) {
            String title = Search_Titles[i]
            title = title.replaceAll(" ", "")
                    .replaceAll("（", "(")
                    .replaceAll("）", ")")
                    .replaceAll("万", "")
                    .replaceAll("股", "")
            String anoContentString = objContentString.replaceAll(" ", "")
                    .replaceAll("（", "(")
                    .replaceAll("）", ")")
                    .replaceAll("万", "")
                    .replaceAll("股", "")

            if (title == anoContentString || anoContentString.contains(title)) {
                return true
            }

        }

        return false
    }

    static boolean strContains(String[] Search_Titles, String objContentString) {
        objContentString = objContentString.replaceAll(" ", "")
                .replaceAll("（", "(")
                .replaceAll("）", ")")
        for (i in 0..<Search_Titles.length) {
            String title = Search_Titles[i]
            title = title.replaceAll(" ", "")
                    .replaceAll("（", "(")
                    .replaceAll("）", ")")

            if (title == objContentString || objContentString.contains(title)) {
                return true
            }
        }
        return false
    }


    //增加，号
    static void replacePoint(TaskElementVO.DrawResultVO resultVO){
        try {
            String resultValue = resultVO.text
            Log.info("RansomAmount_30497_50_transfer_resultValue="+resultValue)

            //900,960.00    原本有小数点
            if(resultValue =~ /.*\.\d{2}$/){
                resultValue = resultValue.replace(",","")
                        .replace(".","")
                        .replace("，","")
                int resultLen = resultValue.length()

                //整数部分
                String integral = resultValue.substring(0 , resultLen - 2)
                //小数部分
                String decimal = resultValue.substring(resultLen - 2 , resultLen)

                //如果逗号出现在字符串的首部,那就去掉逗号
                if(integral.indexOf(",") == 0){
                    integral = integral.substring(1,integral.length())
                }

                //数据格式化
                DecimalFormat df = new DecimalFormat( "###,###" )
                integral = df.format(Integer.valueOf(integral))

                String number = integral + "." + decimal
                resultVO.text = number
            }

            //144.906.892.5
            else if(resultValue =~ /.*\.\d{1}$/){
                resultValue = resultValue.replace(",","")
                        .replace(".","")
                        .replace("，","")
                int resultLen = resultValue.length()

                //整数部分
                String integral = resultValue.substring(0 , resultLen - 1)
                //小数部分
                String decimal = resultValue.substring(resultLen - 1 , resultLen)

                //如果逗号出现在字符串的首部,那就去掉逗号
                if(integral.indexOf(",") == 0){
                    integral = integral.substring(1,integral.length())
                }

                //数据格式化
                DecimalFormat df = new DecimalFormat( "###,###" )
                integral = df.format(Integer.valueOf(integral))

                String number = integral + "." + decimal
                resultVO.text = number
            }

            //90096000
            else{
                DecimalFormat df = new DecimalFormat( "###,###.00" )
                String result = df.format(Integer.valueOf(resultValue))
                resultVO.text = result
            }
            resultVO.businessValue = resultVO.text
            resultVO.type = 1
//            Log.info(">>>>>>>>resultVO={]"+resultVO.text)

        } catch (Exception e) {
            Log.error(e)
        }
    }

}
